package com.daxt.controller.system;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.daxt.common.annotations.LoginAuth;
import com.daxt.common.annotations.LoginUser;
import com.daxt.common.util.DateUtil;
import com.daxt.common.util.HttpWsUtil;
import com.daxt.mapper.external.RequestInfoMapper;
import com.daxt.mapper.sys.*;
import com.daxt.model.dic.ExternalType;
import com.daxt.model.dic.VersionsMarkType;
import com.daxt.model.dto.FourAUserDto;
import com.daxt.model.service.base.param.ChangeDept;
import com.daxt.model.service.base.param.ChangePassword;
import com.daxt.model.service.base.vo.*;
import com.daxt.model.service.external.RequestInfo;
import com.daxt.service.UserService;
import com.daxt.utils.BaseUtil;
import com.daxt.utils.IpUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.daxt.base.common.util.RedisUtil;
import com.daxt.base.common.util.UserInfoUtil;
import com.daxt.common.result.PageInfo;
import com.daxt.common.result.PageUtil;
import com.daxt.common.result.Result;
import com.daxt.common.result.ResultCode;
import com.daxt.common.result.ResultUtil;
import com.daxt.common.util.Md5Util;
import com.daxt.model.service.base.param.EditUser;
import com.daxt.model.service.base.result.UserInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "用户")
@RestController
public class UserController {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private UserFondsMapper userFondsMapper;
    @Autowired
    private UserDeptMapper userDeptMapper;
    @Autowired
    private UserClassifyMapper userClassifyMapper;
    @Autowired
    private UserInfoUtil userInfoUtil;
    @Autowired
    private UserService userService;
    @Autowired
    private UserPostMapper userPostMapper;
    @Autowired
    private RequestInfoMapper requestInfoMapper;
    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private OperationLogMapper operationLogMapper;


    @ApiOperation(value = "获取用户信息", notes = "")
    @GetMapping("/user/info")
    @LoginAuth
    public Result<UserInfo> getUserInfo(@LoginUser UserInfo loginUser, HttpServletRequest request) {

        UserInfo loginInfo = userInfoUtil.getLoginInfo(redisUtil, loginUser);

        /*UserPost userPost = userPostMapper.selectById(loginInfo.getId());
        if(userPost!=null){
            loginInfo.setPostId(userPost.getPostId()+"");
        }*/
//        UserInfo loginInfo = userInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
        // loginInfo.setResouces(null);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, loginInfo);
    }

    @ApiOperation(value = "记录用户登录日志，走单点登录的时候使用", notes = "")
    @GetMapping("/user/login/log")
    @LoginAuth
    public Result<String> getUserLoginLog(@LoginUser UserInfo loginUser, HttpServletRequest request) {

        String ip= IpUtil.getIP(request);
        UserInfo loginInfo = userInfoUtil.getLoginInfo(redisUtil, loginUser);
        OperationLog entity = new OperationLog();
        entity.setOtype("1");
        entity.setOcontent("登录");
        entity.setOperationBy(loginInfo.getUsername());
        entity.setIp(ip);
        entity.setOperationDept(loginInfo.getDeptName());
        entity.setFondsId(loginInfo.getFondsId());
        entity.setCreateTime(LocalDateTime.now());
        operationLogMapper.insert(entity);

        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, null);
    }



    @ApiOperation(value = "获取用户功能", notes = "")
    @GetMapping("/user/getFunction")
    public Result<List<Function>> getResouces(HttpServletRequest request) {
        UserInfo loginInfo = userInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
        List<Function> resouces = loginInfo.getResouces();
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, resouces);
    }

    @ApiOperation(value = "获取列表", notes = "")
    @GetMapping("/user")
    @LoginAuth
    public Result<PageInfo<BaseUser>> list(@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                           @ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                           @ApiParam("") @RequestParam(value = "deptIds", required = false) String deptIds,
                                           @ApiParam("") @RequestParam(value = "keyWord", required = false) String keyWord,
                                           @ApiParam("") @RequestParam(value = "tenantId", required = false) String tenantId) {
        if (pageNum == null || pageSize == null) {
            pageNum = 1;
            pageSize = 10;
        }
        Page<BaseUser> page = new Page<BaseUser>(pageNum, pageSize);
        QueryWrapper<BaseUser> queryWrapper = new QueryWrapper<BaseUser>();

        if (!StringUtils.isEmpty(deptIds)){
            queryWrapper.eq("deptIds",deptIds);
        }
        if (!StringUtils.isEmpty(keyWord)){
            queryWrapper.and(Wrapper -> Wrapper.like("realName", keyWord).or().like("username",keyWord).or().like("mobile",keyWord));
        }

        if (!StringUtils.isEmpty(tenantId))
            queryWrapper.eq("tenantId", tenantId);
        IPage<BaseUser> info = userMapper.selectPage(page, queryWrapper);
        if (info.getRecords() != null && info.getRecords().size() > 0) {
            for (int i = 0; i < info.getRecords().size(); i++) {
                BaseUser baseUser = info.getRecords().get(i);
                QueryWrapper<UserRole> queryUserRole = new QueryWrapper<UserRole>();
                queryUserRole.eq("userId", info.getRecords().get(i).getId());
                List<UserRole> userRoles = userRoleMapper.selectList(queryUserRole);
                baseUser.setUserRole(userRoles);
                QueryWrapper<UserFonds> queryUserFonds = new QueryWrapper<UserFonds>();
                queryUserFonds.eq("userId", info.getRecords().get(i).getId());
                List<UserFonds> userFonds = userFondsMapper.selectList(queryUserFonds);
                baseUser.setUserFonds(userFonds);

                QueryWrapper<UserPost> queryUserPost = new QueryWrapper<UserPost>();
                queryUserPost.eq("id", info.getRecords().get(i).getId());
                List<UserPost> userPosts = userPostMapper.selectList(queryUserPost);
                baseUser.setUserPosts(userPosts);


                QueryWrapper<Dept> queryDept = new QueryWrapper<Dept>();
                queryDept.eq("id", info.getRecords().get(i).getDeptIds());
                List<Dept> depts = deptMapper.selectList(queryDept);
                baseUser.setDepts(depts);

            }
        }
        PageInfo<BaseUser> data = PageUtil.data(info.getPages(), info.getCurrent(), info.getTotal(), info.getRecords());
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, data);
    }

    @ApiOperation(value = "添加", notes = "")
    @PostMapping("/user")
    @LoginAuth
    @Transactional(rollbackFor = Exception.class)
    public Result<String> save(@RequestBody EditUser entity) {
        try {
            BaseUser baseUser = new BaseUser();
            BeanUtils.copyProperties(entity, baseUser);
            if (!StringUtils.isEmpty(baseUser.getPassword()))
                baseUser.setPassword(Md5Util.hash(baseUser.getPassword()));
            baseUser.setCreateTime(LocalDateTime.now());
            QueryWrapper<BaseUser> queryWrapper = new QueryWrapper<BaseUser>();
            queryWrapper.select("id");
            queryWrapper.eq("username", entity.getUsername());
            List<BaseUser> list = userMapper.selectList(queryWrapper);
            if (list != null && list.size() > 0) {
                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "该用户名已存在", null);
            }

            if (StringUtils.isEmpty(baseUser.getPassword())) {
                if(RedisUtil.isAppoint(VersionsMarkType.VERSIONS_4)){
                    baseUser.setPassword(Md5Util.hash("A1b2C3d4@@"));
                }else {
                    baseUser.setPassword(Md5Util.hash("123456"));
                }
            } else {
                baseUser.setPassword(Md5Util.hash(baseUser.getPassword()));
            }
            baseUser.setCreateTime(LocalDateTime.now());
            int rows = userMapper.insert(baseUser);
            userMapper.update(baseUser,new UpdateWrapper<BaseUser>()
                    .set(entity.getDepts()!=null&&entity.getDepts().size()>0,"deptIds",entity.getDepts().toString().substring(1,entity.getDepts().toString().lastIndexOf("]")))
                    .eq("id",baseUser.getId()));
            entity.setId(baseUser.getId());

            List<String> posts = entity.getPosts();
            if(BaseUtil.listIsNotNullElement(posts)){
                Result<String> r = userService.verifyUserPost(baseUser, posts);
                if (r.getCode().equals(ResultCode.RESULT_ERROR.getCode()))return r;
            }


            userService.saveUserRelevance(entity);


//            List<String> roles = entity.getRoles();
//            if (roles != null && roles.size() > 0) {
//                for (String string : roles) {
//                    UserRole userRoleEntity = new UserRole();
//                    userRoleEntity.setRoleId(Long.parseLong(string));
//                    userRoleEntity.setUserId(baseUser.getId());
//                    userRoleMapper.insert(userRoleEntity);
//                }
//            }
//            List<String> fonds = entity.getFonds();
//            if (fonds != null && fonds.size() > 0) {
//                for (String string : fonds) {
//                    UserFonds userRoleEntity = new UserFonds();
//                    userRoleEntity.setFondsId(string);
//                    userRoleEntity.setUserId(baseUser.getId());
//                    userFondsMapper.insert(userRoleEntity);
//                }
//            }
//
//            List<String> depts = entity.getDepts();
//            if (depts != null && depts.size() > 0) {
//                for (String string : depts) {
//                    UserDept userDeptEntity = new UserDept();
//                    userDeptEntity.setDeptId(Long.parseLong(string));
//                    userDeptEntity.setUserId(baseUser.getId());
//                    userDeptMapper.insert(userDeptEntity);
//                }
//            }
//
//            List<String> posts = entity.getPosts();
//            if (posts != null && posts.size() > 0) {
//                Result<String> r = userService.verifyUserPost(baseUser,posts);
//                if(r.getCode().equals(ResultCode.RESULT_ERROR.getCode()))return r;
//                for (String string : posts) {
//                    UserPost userPostEntity = new UserPost();
//                    userPostEntity.setId(baseUser.getId());
//                    userPostEntity.setPostId(Long.parseLong(string));
//                    userPostMapper.insert(userPostEntity);
//                }
//            }






            return ResultUtil.data(rows > 0 ? ResultCode.RESULT_SUCCESS.getCode() : ResultCode.RESULT_ERROR.getCode(), null,
                    null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "操作异常！！！", null);
        }
    }

    @ApiOperation(value = "人员调配", notes = "")
    @PostMapping("/user/deploy")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> deploy(@RequestBody ChangeDept dept){
        try{
            List<Long> userIds = dept.getUserIds();
            if(dept.getDeptId()!=null && userIds.size()>0){

                UpdateWrapper<BaseUser> updateUser=new UpdateWrapper<>();
                updateUser.set("deptIds",dept.getDeptId());
                updateUser.in("id",userIds);
                int rows1=userMapper.update(new BaseUser(), updateUser);

                UpdateWrapper<UserDept> updateUserDept=new UpdateWrapper<>();
                updateUserDept.set("deptId",dept.getDeptId());
                updateUserDept.in("userId",userIds);
                int rows2=userDeptMapper.update(new UserDept(),updateUserDept);

                return ResultUtil.data(rows1 > 0 || rows2 > 0 ? ResultCode.RESULT_SUCCESS.getCode() : ResultCode.RESULT_ERROR.getCode(), null,
                        null);
            }else{
                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "操作异常！！！", null);
            }
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "操作异常！！！", null);
        }
    }

    @ApiOperation(value = "修改", notes = "")
    @PutMapping("/user")
    @LoginAuth
    @Transactional(rollbackFor = Exception.class)
    public Result<String> edit(@RequestBody EditUser entity) {
        try {
            BaseUser baseUser = new BaseUser();
            BeanUtils.copyProperties(entity, baseUser);

            if(null == baseUser.getDeptIds()){
                baseUser.setDeptIds(userMapper.selectById(entity.getId()).getDeptIds());
            }

            List<String> posts = entity.getPosts();
            if(BaseUtil.listIsNotNullElement(posts)){
                Result<String> r = userService.verifyUserPost(baseUser, posts);
                if (r.getCode().equals(ResultCode.RESULT_ERROR.getCode()))return r;
            }


            baseUser.setUpdateTime(LocalDateTime.now());
            int rows = userMapper.updateById(baseUser);
            userMapper.update(baseUser,new UpdateWrapper<BaseUser>()
                    .set(entity.getDepts()!=null&&entity.getDepts().size()>0,"deptIds",entity.getDepts().toString().substring(1,entity.getDepts().toString().lastIndexOf("]")))
                    .eq("id",baseUser.getId()));

            userService.saveUserRelevance(entity);

//            QueryWrapper<UserRole> wrapper = new QueryWrapper<UserRole>();
//            wrapper.eq("userId", entity.getId());
//            userRoleMapper.delete(wrapper);
//            List<String> roles = entity.getRoles();
//            if (roles != null && roles.size() > 0) {
//                for (String string : roles) {
//                    UserRole userRoleEntity = new UserRole();
//                    userRoleEntity.setRoleId(Long.parseLong(string));
//                    userRoleEntity.setUserId(entity.getId());
//                    userRoleMapper.insert(userRoleEntity);
//                }
//            }
//
//            QueryWrapper<UserFonds> wrapperFondsId = new QueryWrapper<UserFonds>();
//            wrapperFondsId.eq("userId", entity.getId());
//            userFondsMapper.delete(wrapperFondsId);
//            List<String> fonds = entity.getFonds();
//            if (fonds != null && fonds.size() > 0) {
//                for (String string : fonds) {
//                    UserFonds userRoleEntity = new UserFonds();
//                    userRoleEntity.setFondsId(string);
//                    userRoleEntity.setUserId(baseUser.getId());
//                    userFondsMapper.insert(userRoleEntity);
//                }
//            }
//
//            userPostMapper.deleteById(entity.getId());
//            List<String> posts = entity.getPosts();
//            if (posts != null && posts.size() > 0) {
//                Result<String> r = userService.verifyUserPost(baseUser,posts);
//                if(r.getCode().equals(ResultCode.RESULT_ERROR.getCode()))return r;
//                for (String string : posts) {
//                    UserPost userPostEntity = new UserPost();
//                    userPostEntity.setId(baseUser.getId());
//                    userPostEntity.setPostId(Long.parseLong(string));
//                    userPostMapper.insert(userPostEntity);
//                }
//            }


            return ResultUtil.data(rows > 0 ? ResultCode.RESULT_SUCCESS.getCode() : ResultCode.RESULT_ERROR.getCode(), null,
                    null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "操作异常！！！", null);
        }
    }

    @ApiOperation(value = "删除", notes = "")
    @DeleteMapping("/user/{userId}")
    @LoginAuth
    @Transactional(rollbackFor = Exception.class)

    public Result<String> del(@PathVariable("userId") String userId) {
        try {
            QueryWrapper<UserRole> wrapper = new QueryWrapper<UserRole>();
            wrapper.eq("userId", userId);
            userRoleMapper.delete(wrapper);

            QueryWrapper<UserDept> wrapperUserDept = new QueryWrapper<UserDept>();
            wrapperUserDept.eq("userId", userId);
            userDeptMapper.delete(wrapperUserDept);
            QueryWrapper<UserFonds> wrapperFondsId = new QueryWrapper<UserFonds>();
            wrapperFondsId.eq("userId", userId);
            userFondsMapper.delete(wrapperFondsId);
            userPostMapper.deleteById(userId);
            int rows = userMapper.deleteById(userId);
            return ResultUtil.data(rows > 0 ? ResultCode.RESULT_SUCCESS.getCode() : ResultCode.RESULT_ERROR.getCode(), null,
                    null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "操作异常！！！", null);
        }
    }

    @ApiOperation(value = "用户分配全宗", notes = "")
    @PostMapping("/user/setFonds")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> setFonds(@RequestBody List<UserFonds> entity) {
        if (entity != null && entity.size() > 0) {
            for (UserFonds userFonds : entity) {
                userFondsMapper.insert(userFonds);
            }
            return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, null);
        } else {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), null, null);
        }
    }


    /**
     * @description:
     * @author: lig
     * @date: 2021/6/10
     */
    @ApiOperation(value = "用户分配档案门类的数据权限", notes = "")
    @PostMapping("/user/setDataPrivilege")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> setDataPrivilege(@RequestBody List<UserClassify> entity) {
        if (BaseUtil.listIsNotNullElement(entity)) {
            QueryWrapper<UserClassify> qWrapper = new QueryWrapper<UserClassify>();
            qWrapper.eq("roleId", entity.get(0).getRoleId());
            userClassifyMapper.delete(qWrapper);
        }
        if (entity != null && entity.size() > 0) {
            for (UserClassify userClassify : entity) {
                if (null == userClassify.getClassifyId()) continue;
                userClassifyMapper.insert(userClassify);
            }
        }
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, null);
    }


    /**
     * @description:
     * @author: lig
     * @date: 2021/6/10
     */
    @ApiOperation(value = "确认密码", notes = "")
    @PostMapping("/verifyPassword")
    public Result<String> verifyPassword(@RequestBody ChangePassword changePassword, HttpServletRequest request) {
        UserInfo loginInfo = userInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
        if (loginInfo == null) {
            return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(), ResultCode.NOT_LOGIN.getMes(), null);
        }
        if (!Md5Util.hash(changePassword.getAgainPassword()).equals(loginInfo.getPassword())) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "密码不正确", null);
        }

        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "密码正确", null);
    }

    /**
     * @description:
     * @author: lig
     * @date: 2021/6/10
     */
    @ApiOperation(value = "获取用户分配档案数据权限", notes = "")
    @GetMapping("/user/getDataPrivilege/{roleId}")
    @Transactional(rollbackFor = Exception.class)
    public Result<List<UserClassify>> getDataPrivilege(@PathVariable("roleId") String roleId, HttpServletRequest request) {

        UserInfo loginInfo = userInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
        if (loginInfo == null) {
            return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(), ResultCode.NOT_LOGIN.getMes(), null);
        }

        List<UserClassify> list = new ArrayList<>();

        QueryWrapper<UserClassify> ucQw = new QueryWrapper<UserClassify>();
        ucQw.eq("roleId", roleId);
        list = userClassifyMapper.selectList(ucQw);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, list);


    }


    @ApiOperation(value = "同步外部用户信息", notes = "")
    @GetMapping("/user/sync")
    @Async("cloudExecutor")
    @Transactional(rollbackFor = Exception.class)
    public void syncUserInfo() {

        List<FourAUserDto> fourAUserDtoList = new ArrayList<>();

        String number = "1000";

        QueryWrapper<RequestInfo> qwInfo = new QueryWrapper();
        qwInfo.eq("type",ExternalType.TYPE_1.getKey());
        qwInfo.eq("parse","true");
        qwInfo.orderByDesc("id");
        List<RequestInfo> rInfoList = requestInfoMapper.selectList(qwInfo);
        String updateTime = "";
        if(BaseUtil.listIsNotNullElement(rInfoList)){
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DateUtil.DateFormat.YYYY_MM_DD_HH_mm_ss.getValue());
            updateTime = rInfoList.get(0).getCreateTime().format(formatter);
        }

        //追加同步  根据更新时间
        for (int i = 1; i < 100; i++) {
            RequestInfo rInfo = new RequestInfo();
            rInfo.setType(ExternalType.TYPE_1.getKey());
            rInfo.setUrl("http://www.sxlq.com:4572/lq4a_queryuser?wsdl");

            StringBuffer requestSb = new StringBuffer();
            requestSb.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n");
            requestSb.append("<soapenv:Body>\n");


            if(StringUtils.isEmpty(updateTime)){
                //同步
                requestSb.append("<selAllUser xmlns=\"http://service.sx4a.dhcc.com/\">\n");
                requestSb.append("<arg0 xmlns=\"\">\n");
                requestSb.append("<![CDATA[");
                requestSb.append("<SelAllUserRequest>");
                requestSb.append("<uid>all</uid>");
                requestSb.append("<batch>" + i + "</batch>");
                requestSb.append("<number>" + number + "</number>");
                requestSb.append("</SelAllUserRequest>");
                requestSb.append("]]>");
                requestSb.append("</arg0>\n");
                requestSb.append("</selAllUser>\n");

            }else{
                //追加同步
                requestSb.append("<selAllUserAfter xmlns=\"http://service.sx4a.dhcc.com/\">\n");
                requestSb.append("<arg0 xmlns=\"\">\n");
                requestSb.append("<![CDATA[");
                requestSb.append("<SelAllUserRequest>");
                requestSb.append("<uid>all</uid>");
                requestSb.append("<batch>" + i + "</batch>");
                requestSb.append("<number>" + number + "</number>");
                requestSb.append("<updateTime>" + updateTime + "</updateTime>");
                requestSb.append("</SelAllUserRequest>");
                requestSb.append("]]>");
                requestSb.append("</arg0>\n");
                requestSb.append("</selAllUserAfter>\n");
            }


            requestSb.append("</soapenv:Body>\n");
            requestSb.append("</soapenv:Envelope>");
            rInfo.setRequestStr(requestSb.toString());
            rInfo = HttpWsUtil.syscUserData(rInfo);
            requestInfoMapper.insert(rInfo);
            List<FourAUserDto> tempList = (List<FourAUserDto>) rInfo.getParseStr();
            if (BaseUtil.listIsNotNullElement(tempList)){
                fourAUserDtoList.addAll(tempList);
            } else{
                break;
            }

            System.out.println("==========执行批次完："+i);
        }

        fourAUserDtoList.forEach((FourAUserDto dto) -> {
            if (StringUtils.isEmpty(dto.getStatus()) || !dto.getStatus().equals("1")) return;

            QueryWrapper<BaseUser> qw = new QueryWrapper<BaseUser>();
            qw.eq("extId", dto.getPerId());
            BaseUser bean = userMapper.selectOne(qw);
            if (null == bean) {
                bean = new BaseUser();
                bean.setExtId(dto.getPerId());
            }
            bean.setUsername(dto.getLoginName());
            bean.setRealName(dto.getPerName());
            bean.setDeptIds(Long.parseLong(dto.getDeptId()));

            userService.saveOrUpdate(bean);


            QueryWrapper<UserDept> udQw = new QueryWrapper<>();
            udQw.eq("userId", bean.getId());
            UserDept ud = userDeptMapper.selectOne(udQw);
            if (null == ud) {
                ud = new UserDept();
                ud.setUserId(bean.getId());
                ud.setDeptId(Long.parseLong(dto.getDeptId()));
                userDeptMapper.insert(ud);
            }else{
                ud.setDeptId(Long.parseLong(dto.getDeptId()));
                userDeptMapper.updateById(ud);
            }


        });

    }


    @ApiOperation(value = "同步外部用户信息,新", notes = "")
    @GetMapping("/user/newsync")
    @Async("cloudExecutor")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> syncUserInfoNew() {
        userService.syncUserInfoNew(null);
        return ResultUtil.success();
    }


//    @ApiOperation(value = "设置岗位", notes = "")
//    @PostMapping("/user/addPost/")
//    @Transactional(rollbackFor = Exception.class)
//    public Result<String> addPost(@RequestBody UserPost userPost) {
////    public Result<String> addPost(@PathVariable("userId") String userId,@PathVariable("postId") String postId) {
//
//        UserPost up = userPostMapper.selectById(userPost.getId());
//        int i = 0 ;
//        if(null == up){
//            i = userPostMapper.insert(userPost);
//        }else{
//            i = userPostMapper.updateById(userPost);
//        }
//        return ResultUtil.result(i);
//    }


}
